package org.jfedor.nxtremotecontrol;

/*
 * TODO:
 * 
 * NXTTalker의 초기화 클레스
 */

import java.io.IOException;
import java.util.Set;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.util.Log;
import android.os.Handler;

public class NXTConnector extends Thread {
	
	private BluetoothAdapter mBtAdapter;
	private String mDeviceAddress;
	private NXTTalker mNXTTalker;
    public static final int MESSAGE_TOAST = 1;
    public static final int MESSAGE_STATE_CHANGE = 2;
    public static final int STATE_NONE = 0;
    public static final int STATE_CONNECTING = 1;
    public static final int STATE_CONNECTED = 2;
    private Handler mHandler;
    
    
	public NXTConnector(Handler handler) {
		mBtAdapter = BluetoothAdapter.getDefaultAdapter();
		mDeviceAddress = null;
		mNXTTalker = null;	
		mHandler = handler;
	}
	
    public NXTTalker getmNXTTalker() {
		return mNXTTalker;
	}

	public void run() {
	    	while(true){
	    		if(mDeviceAddress == null){
	    			mDeviceAddress = getAddress();
	    		} else if("error".equals(mDeviceAddress)){
	    			// 에러 처리
	    			Log.d("NXTConnector","getAddress() 에러");
	    		} else{
	    			Log.d("NXTConnector","getAddress() 성공");
	    			break;
	    		}   		
	    	}
	    	BluetoothDevice device = mBtAdapter.getRemoteDevice(mDeviceAddress);
	    	Log.d("NXTConnector","getRemoteDevice 성공");
	    	mNXTTalker = new NXTTalker(mHandler);
	    	mNXTTalker.connect(device);
	    	return;
    }
    
    public String getAddress(){
		Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();        
		if (pairedDevices.size() > 0) {
		    for (BluetoothDevice device : pairedDevices) {
		        if (device.getBluetoothClass().getDeviceClass() == BluetoothClass.Device.TOY_ROBOT) {
		        		return device.getAddress();
		        }
		    }
		    return "error";
		} 
		else 
			return "error";
    }
}
